<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片内容 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="9">
          <!-- 搜索框 -->
          <el-input
            placeholder="请输入内容"
            v-model="searchInfo"
            clearable=""
            @clear="searchUser"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchUser"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table
        :data="userList"
        style="width: 100%"
        stripe
        border
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
      >
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template v-slot="{ row }">
            <!-- {{ row }} 查看row -->
            <el-switch v-model="row.mg_state" @change="userStateChanged(row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template v-slot="{ row }">
            <!-- {{ row }} -->
            <!-- 编辑按钮 -->
            <el-tooltip
              effect="dark"
              content="编辑"
              placement="top"
              :open-delay="1000"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 删除按钮 -->
            <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :open-delay="1000"
              :enterable="false"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUserById(row)"
              ></el-button>
            </el-tooltip>

            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :open-delay="1000"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRoleDialog(row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="dialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
        :status-icon="true"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editClosed"
    >
      <!-- 内容区域 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
        :status-icon="true"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUsersInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <p>当前用户：{{ userInfo.username }}</p>
      <p>当前角色：{{ userInfo.role_name }}</p>
      <p>
        分配新角色：
        <el-select v-model="selectedRoleId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Users',
  created() {
    this.getUserList()
  },
  data() {
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (!regEmail.test(value)) {
        return callback(new Error('请输入正确的邮箱'))
      }
      callback()
    }

    return {
      queryInfo: {
        query: '',
        // 当前页码
        pagenum: 1,
        //  每页多少条数据
        pagesize: 2
      },
      // 用户数据
      userList: [],
      total: 0,
      // 暂时储存input输入内容
      searchInfo: '',
      // 添加用户对话框是否显示
      dialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 15, message: '长度在 5 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: this.checkMobile, trigger: 'blur' }
        ]
      },
      // 编辑用户对话框是否显示
      editDialogVisible: false,
      // 查询到的用户信息
      editForm: {},
      // 修改表单规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: this.checkMobile, trigger: 'blur' }
        ]
      },
      // 是否显示分配角色对话框
      setRoleDialogVisible: false,
      // 储存对应用户的信息
      userInfo: {},
      // 存放角色列表信息
      rolesList: [],
      // 选中新角色id值
      selectedRoleId: ''
    }
  },
  methods: {
    // 获取数据列表
    async getUserList() {
      const { data: res } = await this.$http.get('/users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.searchUser()
    },

    // 监听 pagenum 改变的事件
    handleCurrentChange(newPage) {
      // 记录首页此时的页码
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听 switch 开关的变化
    async userStateChanged(row) {
      const { data: res } = await this.$http.put(
        `users/${row.id}/state/${row.mg_state}`
      )
      if (res.meta.status !== 200) {
        res.mg_state = !res.mg_state
        return this.$message.error('修改用户状态失败')
      }
      this.$message.success('修改用户状态成功')
    },
    // 刷新列表
    searchUser() {
      // 将搜索框的值赋给query
      this.queryInfo.query = this.searchInfo
      // 若返回首页则回到原来记录的页码
      this.queryInfo.pagenum = 1
      this.getUserList()
    },
    // 检查手机号码是否合法
    checkMobile(rule, value, callback) {
      const regMobile = /^(0|86|17951)?(13[0-9]|14[57]|15[0-9]|17[678]|18[0-9])[0-9]{8}$/
      if (!regMobile.test(value)) {
        return callback(new Error('请输入正确的号码'))
      }
      callback()
    },
    // 添加用户框关闭后重置
    dialogClosed() {
      this.$refs.addFormRef.resetFields()
    },

    // 点击确定，添加新用户
    addUser() {
      // 校验表单
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false
        // 校验成功，可以发起添加用户的网络请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加用户成功')
        // 隐藏添加用户对话框
        this.dialogVisible = false
        // 重新获取用户数据
        this.searchUser()
      })
    },
    // 打开编辑对话框，根据用户id查询用户数据
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('用户数据获取失败')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 编辑对话框关闭后重置
    editClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 点击确定，发送修改内容
    editUsersInfo() {
      // 校验表单
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return false
        }
        // 校验通过进行发送
        const { data: res } = await this.$http.put(
          `users/${this.editForm.id}`,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        // 判断是否发送成功
        if (res.meta.status !== 200) {
          return this.$message.error('数据更新失败')
        }
        // 更新成功
        this.editDialogVisible = false
        // 刷新数据
        this.searchUser()
        // 提示成功
        this.$message.success('数据更新成功')
      })
    },
    // 删除用户
    async removeUserById(row) {
      // 确认是否删除
      const res = await this.$confirm(
        '此操作将永久删除' + row.username + ', 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 若确认，res 返回字符串 "confirm"
      // 若取消，res 返回字符串 "cancel"
      if (res !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      // 删除用户
      const { data: result } = await this.$http.delete(`users/${row.id}`)
      // 判断是否删除失败
      if (result.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      // 删除成功后，刷新数据
      this.searchUser()
      // 成功提示
      this.$message.success('删除成功')
    },
    // 打开分配角色对话框
    async setRoleDialog(row) {
      // 储存用户信息
      this.userInfo = row
      // 获取角色列表
      const { data: res } = await this.$http.get('roles')
      // 获取失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      // 获取成功
      this.rolesList = res.data
      // 显示对话框
      this.setRoleDialogVisible = true
    },
    // 分配角色
    async setRoleInfo() {
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectedRoleId
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('角色分配失败')
      }
      // 分配成功
      this.$message.success('角色分配成功')
      // 刷新列表
      this.searchUser()
      // 关闭对话框
      this.setRoleDialogVisible = false
    },
    // 关闭分配角色对话框后清空数据
    setRoleDialogClosed() {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>
<style lang="less" scoped>
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 15px;
}
</style>
